<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/3
 * Time: 10:53
 */

namespace app\applet\model;


use think\Config;
use think\Db;
use think\Exception;
use WeixinPay\WeixinPay;
class Member
{
    public function bindPhoneWx($data)
    {
        $id = get_header_id("token");
        #获取会话秘钥
        $sessionKey = Db::name("member")
            ->field("session_key")
            ->where(['member_id'=>$id])
            ->find();

        $appid = (Config::get("applet"))['tenant']['appid'];
        $sessionKey = $sessionKey['session_key'];

        $encrypted_data = $data['encrypted_data'];
        $iv = $data['iv'];


        #调接口,解析加密数据
        include ROOT_PATH."extend".DS."WeChatEncry".DS."wxBizDataCrypt.php";
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encrypted_data, $iv, $data );

        if ($errCode == 0) {
            $data = json_decode($data,true);
            $phone = $data['purePhoneNumber'];
            Db::name("member")
                ->where(['member_id'=>$id])
                ->update(['mobile'=>$phone]);

        } else {
            returnJson(-2004,"解析错误,错误码为:".$errCode);
        }



    }
    public function bindPhone($data)
    {
        $member_id= get_header_id("token");
        $phone = $data['phone'];
        $code = $data['code'];
        #查询验证码是否存在5分钟有效
        $msg_code = Db::name("code_msg")
            ->field("id,code,create_time")
            ->where(['phone'=>$phone,'status'=>0])
            ->order(['id'=>'desc'])
            ->find();
        if($msg_code === NULL)
        {
            returnJson(-2004,"当前无有效验证码");
        }
        if($msg_code['create_time'] + 5 * 60 < time())
        {
            returnJson(-2004,"当前验证码已过期,请重新发送");
        }
        if($msg_code['code'] != $code)
        {
            returnJson(-2004,"验证码错误");
        }
        #通过验证, 数据入库
        Db::name("member")
            ->where(['member_id'=>$member_id])
            ->update(['mobile'=>$phone]);
        #修改验证码状态
        Db::name("code_msg")
            ->where(['id'=>$msg_code['id']])
            ->update(['status'=>1,"update_time"=>time()]);
    }
    public function isPhone()
    {
        $member_id= get_header_id("token");
        $member = Db::name("member")
            ->field("mobile")
            ->where(['member_id'=>$member_id])
            ->find();
        if($member['mobile'] === "")
        {
            $data['status'] = 0;
        }else{
            $data['status'] = 1;
        }
        return $data;

    }
    //zlc-人脉名片行业分类
    public function industryList()
    {
        $data = Db::name("industry")
            ->field("industry_id,industry_name")
            ->where('parent_id',0)
            ->order(['industry_id'=>'asc'])
            ->select();
        foreach ($data as $k=>&$v)
        {
            $data[$k]['industry_name']  = str_replace("／","/",$v['industry_name']);
            $data[$k]['industry_name']  = str_replace("（","(",$data[$k]['industry_name']);
            $data[$k]['industry_name']  = str_replace("）",")",$data[$k]['industry_name']);

            $data[$k]['childList'] = Db::name("industry")
                ->field("industry_id,industry_name")
                ->where('parent_id',$v['industry_id'])
                ->order(['industry_id'=>'asc'])
                ->select();

        }
        return $data;
    }
    /**
     * 唯一性判断
     */
    public function only($member_id)
    {
        $count = Db::name("member_info")
            ->where(['member_id'=>$member_id,'status'=>['neq',0]])
            ->count();
        if($count)
        {
            returnJson(-2004,'已提交实名认证申请');
        }

    }
    /**
     * 个人中心实名认证
     */
    public function realName($data)
    {
        $member_id=$data['member_id'];
        $phone = $data['phone'];
        $code = $data['code'];
        #查询验证码是否存在5分钟有效
        $msg_code = Db::name("code_msg")
            ->field("id,code,create_time")
            ->where(['phone'=>$phone,'status'=>0])
            ->order(['id'=>'desc'])
            ->find();
        if($msg_code === NULL)
        {
            returnJson(-2004,"当前无有效验证码");
        }
        if($msg_code['create_time'] + 5 * 60 < time())
        {
            returnJson(-2004,"当前验证码已过期,请重新发送");
        }
        if($msg_code['code'] != $code)
        {
            returnJson(-2004,"验证码错误");
        }
        Db::startTrans();
        try {
            Db::name("member")
                ->where(['member_id'=>$member_id])
                ->update(['mobile'=>$data['phone']]);
            unset($data['phone']);
            unset($data['code']);

            $one=Db::name("member_info")
                ->where('member_id',$member_id)->find();
            if(empty($one)){
                Db::name("member_info")
                    ->insert($data);
            }else{
                Db::name("member_info")
                    ->where('member_id',$member_id)
                    ->update(['status'=>2,'real_name'=>$data['real_name'],
                        'card'=>$data['card'],'card_just'=>$data['card_just'],'card_back'=>$data['card_back']]);
            }


            //修改验证码状态
            Db::name("code_msg")
                ->where(['id'=>$msg_code['id']])
                ->update(['status'=>1,"update_time"=>time()]);

            Db::commit();
            unset($_SESSION['msg_code']);
            return true;
        }catch (Exception $e){
            Db::rollback();
            return false;
        }


    }
    /**
     * @param $data array 用户登录数据
     * @return int $member_id  自增主键id
     */
    public function memberAdd($data)
    {

        $tm=time();
        $end_time=$tm+15*365*24*3600;
        Db::startTrans();
        try{
            $member_id = Db::name("member")
                ->insertGetId($data);
            if($member_id<=0){
                throw new Exception("新增失败8");
            }
            $invt_code =self::createCode($member_id);
            //获取推荐人
           if(!empty($data['father_code'])){
               $father_code=$data['father_code'];
           }
            $updMember=['invt_code'=>$invt_code];

            if(!empty( $father_code)){

                $parentInfo=Db::name('member')->where(['invt_code'=>$father_code])->find();
                if(!empty($parentInfo)){
                    $updMember['father_code']=$father_code;
                    $updMember['uid_1']=$parentInfo['member_id'];
                    $updMember['uid_2']=$parentInfo['uid_1'];
                }
            }
            $nums=Db::name("member")
                ->where(['member_id'=>$member_id])
                ->update($updMember);
            if($nums<=0){
                throw new Exception("新增失败7");
            }
            if(!empty($parentInfo)){

                $uid_1=$parentInfo['member_id'];
            }

            //赠送金币
            //注册奖
            $amount=Db::name("system_config")->where(['field_name'=>'reg_coin'])->value("field_value");
            $asset_log = ['member_id' => $member_id, 'type' => 1, 'amount' =>$amount,'source_type' => 2,
                'description' => "会员注册", "change_type" => 2, 'log_type_id' => 61,
               'create_time' => $tm, 'update_time' => $tm
            ];

            $nums=Db::name("member_asset_log")->insert($asset_log);

            if($nums<=0){
                throw new Exception("新增失败6");
            }

            //注册奖励 发送消息
            $msg['create_time']=time();
            $msg['member_id']=$member_id;
            $msg['title']='奖励到帐通知';
            $msg['content']="您获得注册奖励金币".$amount."，请及时查看！";
            $msg['object_type']=2;
            $msg['object_arr']=$member_id;
            $msg['class_type']=14;
            Db::name('message')->insert($msg);


            //用户资产更新
            $member_asset=['member_id'=>$member_id,
                'coin'=>$amount,'create_time'=>$tm,'update_time'=>$tm];

            $nums=Db::name("member_asset")->insert( $member_asset);

            if($nums<=0){
                throw new Exception("新增失败5");
            }
            //直推奖
            if(!empty($parentInfo)&&$uid_1>0){
                $invtAmount=Db::name("system_config")->where(['field_name'=>'invt_coin'])->value("field_value");
                $asset_log = ['member_id' =>$uid_1, 'type' => 1, 'amount' =>$invtAmount,
                    'source_type' => 2, 'description' => "直推荐人奖", "change_type" => 2, 'log_type_id' => 28,
                    'create_time' => $tm, 'update_time' => $tm];
                $nums=Db::name("member_asset_log")->insertGetId($asset_log);
                if($nums<=0){
                    throw new Exception("新增失败4");
                }

                //直推奖励--发送消息
                $msg2['create_time']=time();
                $msg2['member_id']=$member_id;
                $msg2['title']='奖励到帐通知';
                $msg2['content']="您获得推荐奖励金币".$invtAmount."，请及时查看！";
                $msg2['object_type']=2;
                $msg2['object_arr']=$uid_1;
                $msg2['class_type']=14;
                Db::name('message')->insert($msg2);

                $nums=Db::name("member_asset")->where(['member_id'=>$uid_1])->setInc('coin',$invtAmount);
                if($nums<=0){
                    throw new Exception("新增失败3");
                }
            }

            //用户等级
            $member_grade=['member_id'=>$member_id,'grade_type'=>1,'start_time'=>$tm,'end_time'=>$end_time];
            $nums=Db::name("member_grade")->insert($member_grade);
            if($nums<=0){
                throw new Exception("新增失败2");
            }
            //获取上级用户邀请人数
            if(!empty($parentInfo)&&$uid_1>0){
                $invNums=Db::name("member")->where(['uid_1'=>$uid_1])->count();
                if($invNums>0){
                    //最高可释放积分
                    $n=floor($invNums/10);
                    if($n>=10){//邀请人数超过一百
                        $max_release_score=10000000000;
                        $m=$n%10;
                        if($m==0&&!empty($parentInfo)&&$uid_1>0){

                            $asset_log = ['member_id' =>$uid_1, 'type' => 1, 'amount' =>100,
                                'source_type' => 2, 'description' => "直推荐人奖", "change_type" => 2, 'log_type_id' => 28,
                                'create_time' => $tm, 'update_time' => $tm];
                            $nums=Db::name("member_asset_log")->insertGetId($asset_log);
                            if($nums<=0){
                                throw new Exception("新增失败4");
                            }
                            $nums=Db::name("member_asset")->where(['member_id'=>$uid_1])->setInc('coin',$invtAmount);
                            if($nums<=0){
                                throw new Exception("新增失败3");
                            }
                        }

                    }else{
                        $max_release_score=$n*10000;
                    }
                    $max_thaw_score=Db::name("member_asset")->where(['member_id'=>$uid_1])->value("max_thaw_score");
                    if($n>0&&$max_release_score>0&&$max_thaw_score!=$max_release_score){

                        $num=Db::name("member_asset")->where(['member_id'=>$uid_1])->update(['max_thaw_score'=>$max_release_score]);
                        if($num<=0){
                            throw new Exception("新增失败1");
                        }
                    }

                }
            }

            // 提交事务
            Db::commit();
            return $member_id;
        }catch (Exception $e)
        {
            Db::rollback();
            return false;
        }
    }
    /**
     * 生成一个唯一邀请码
     */
    private function createCode($user_id)
    {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        $num = $user_id;
        $code = '';
        while ( $num > 0) {
            $mod = $num % 35;
            $num = ($num - $mod) / 35;
            $code = $source_string[$mod].$code;
        }
        if(empty($code[3]))
            $code = str_pad($code,6,'0',STR_PAD_LEFT);
        return $code;
    }
    /**
     * @param  $openid  string  openid
     * @return $member_id  string  用户id或者null
     */
    public function memberStatus($openid)
    {
        $data = Db::name("member")
            ->field("member_id,is_enable,is_delete")
            ->where(['openid'=>$openid])
            ->find();
        if($data == NULL)
        {

        }else if($data['is_enable'] == 2)
        {
            returnJson(-2004,'该用户已被禁用, 请联系管理');
        }else if($data['is_delete'] == 2)
        {
            returnJson(-2004,'该用户已被清除, 请联系管理');
        }else{
            return $data['member_id'];
        }

    }

    /**
     * 个人中心人脉名片修改
     */
    public function contactCard($data,$id)
    {

        $info['avatarUrl']=$data['avatarUrl'];
        $info['gender']=$data['gender'];
        $info['nickName']=$data['real_name'];

        $m_data['real_name']=$data['real_name'];
        $m_data['birth_date']=$data['birth_date'];
        $m_data['social_idy']=$data['social_idy'];
        $m_data['company']=$data['company'];
        $m_data['com_post']=$data['com_post'];
        $m_data['industry']=$data['industry'];
        $m_data['address']=$data['address'];
        $m_data['signature']=$data['signature'];

        $one=Db::name('member_info')->where('member_id',$id)->find();
        if(empty($one)){
            $m_data['member_id']=$id;

            $res=Db::name("member_info")
                ->insert($m_data);
        }else{
            $res=Db::name("member_info")
                ->where('member_id',$id)
                ->update($m_data);
        }


        $res2=Db::name("member")
            ->where('member_id',$id)
            ->update($info);
        $return=true;
        if($res===false || $res2===false){
            $return=false;
        }
        return $return;
    }

    /**
     * 个人中心人脉名片查询
     */
    public function contactCardSelect($id)
    {
        $data=Db::name("member_info")->alias('mi')
            ->field('m.gender,m.avatarUrl,mi.real_name,mi.birth_date,mi.social_idy,mi.company,
            mi.com_post,mi.industry,mi.address,mi.signature')
            ->join('member m','m.member_id=mi.member_id')
            ->where('m.member_id',$id)
            ->find();
        return $data;
    }

    /**
     * 验证用户是否提交股东认证
     */
    public function checkPartner($member_id){
        $count=Db::name('partner_certification')
            ->where('member_id',$member_id)
            ->count();
        if($count>0){
            returnJson(-2004,'已提交股东认证申请');
        }
    }

    /**
     * 个人中心股东认证提交
     */
    public function partner($data){
        Db::name("partner_certification")
            ->insert($data);
        return true;
    }

    /**
     * 意见反馈提交
     */
    public function feedback($data){
        Db::name("feedback")
            ->insert($data);
        return true;
    }

    /**
     * 意见反馈列表
     */
    public function feedList($page,$page_size,$member_id){
        $data=Db::name("feedback")->alias('f')
            ->field('m.nickname,m.avatarUrl,f.f_id,f.content,f.create_time')
            ->join('member m','m.member_id=f.member_id')
            ->where('f.member_id',$member_id)
            ->page($page,$page_size)
            ->select();
//            ->paginate($page_size, false, [
//                'page' => $page,
//            ])->toArray();

        $total_num = Db::name("feedback")->alias('f')
            ->join('member m','m.member_id=f.member_id')
            ->where('f.member_id',$member_id)
            ->count();
        if($total_num>0){
            $t_page=ceil($total_num / $page_size);
        }else{
            $t_page=0;
        }
        $list['current_page'] = $page;
        $list['total_page'] =$t_page;
        $list['page_num'] = $page_size;
        $list['total_num'] = $total_num;
        $list['data'] = $data;
        return $list;
    }

    /**
     * 意见反馈详情
     */
    public function feedDetail($member_id,$id){
        $data=Db::name("feedback")->alias('f')
            ->field('m.nickname,m.avatarUrl,f.content,f.create_time,img_list')
            ->join('member m','m.member_id=f.member_id')
            ->where(['f.member_id'=>$member_id,'f.f_id'=>$id])
            ->find();

        //$data['img_list'] = json_decode($data['img_list'],true);
        //$data['create_time']=date('Y-m-d H:i:s',$data['create_time']);
//        $real_name=$this->checkMemberName($member_id);
//        if(!empty($real_name)){
//            $data['nickname']=$real_name;
//        }
        return $data;
    }

    /**
     * 查询用户是否实名认证以及用户真实姓名
     */
    public function checkMemberName($member_id){
        $one=Db::name("member_info")
            ->where(['member_id'=>$member_id,'status'=>1])
            ->find();
        if(!empty($one)){
            $real_name=$one['real_name'];
        }else{
            $real_name='';
        }
        return $real_name;
    }


    /**
     * 个人中心页面数据
     */
    public function pCenter($member_id){
        $data=Db::name("member")->alias('m')
            ->field('m.avatarUrl,m.nickname,mi.social_idy,mi.company,
            mi.com_post,mi.signature,mi.status')
            ->join('member_info mi','m.member_id=mi.member_id','left')
            ->where('m.member_id',$member_id)
            ->find();
        if(!isset($data['social_idy']) || empty($data['social_idy'])){
            $data['social_idy']='';
        }
        if(!isset($data['company']) || empty($data['company'])){
            $data['company']='';
        }
        if(!isset($data['com_post']) || empty($data['com_post'])){
            $data['com_post']='';
        }
        if(!isset($data['signature']) || empty($data['signature'])){
            $data['signature']='';
        }
        if(!isset($data['status']) || empty($data['status'])){
            $data['status']=0;
        }

        //$data['company']=isset($data['company'])?null:'';
        //$data['com_post']=isset($data['com_post'])?null:'';
        //$data['signature']=isset($data['signature'])?null:'';
        //$data['status']=isset($data['status'])?null:0;
        //获取会员等级
        $memGrade=Db::name("member_grade")->where(['member_id'=>$member_id,'start_time'=>['elt',time()],'end_time'=>['egt',time()]])->order("grade_type desc,grade_id desc ")->limit(1)->find();
        $member_level=1;
        if(!empty($memGrade)){
            $member_level=$memGrade['grade_type'];
        }

        if($member_level==1){//普通会员
            $expire_day="";
            $payScore=Db::name("system_config")->where(['field_name'=>'sliver_annual_fee'])->value("field_value");
            //获取会员积分
            $score=Db::name("member_asset")->where(['member_id'=>$member_id])->value("score");
            if($score>=$payScore){//升级为银卡会员
                Db::startTrans();
                $tm=time();
                try{
                    $asset_log = ['member_id' => $member_id, 'type' => 2, 'amount' =>  $payScore ,
                        'source_type' => 2, 'description' => "升级银卡", "change_type" => 1, 'log_type_id' => 12,
                        'relation_id' => 0, 'create_time' => $tm, 'update_time' => $tm];
                    $num=Db::name("member_asset_log")->insert($asset_log);
                    if($num<=0){
                        throw new Exception("更新失败");
                    }
                    $num=Db::name("member_asset")->where(['member_id'=>$member_id,'score'=>['egt',$payScore]])->setDec("score",$payScore);
                    if($num<=0){
                        throw new Exception("更新失败");
                    }
                    $end_time=365*24*3600+strtotime(date('Y-m-d',strtotime('+1 day')));;
                    //升级银卡
                    $num=Db::name("member_grade")
                        ->insert(['member_id'=>$member_id,'grade_type'=>2,'start_time'=>$tm,'end_time'=>$end_time]);
                    if($num<=0){
                        throw new Exception("更新失败10");
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                }
                $memGrade=Db::name("member_grade")
                    ->where(['member_id'=>$member_id,'start_time'=>['elt',time()],'end_time'=>['egt',time()]])
                    ->order("grade_type desc,grade_id desc")->limit(1)->find();
                if(!empty($memGrade)){
                    $member_level=$memGrade['grade_type'];
                    $expire_day=$memGrade['end_time'];
                }
            }

        }else{
            $expire_day=$memGrade['end_time'];
        }
        $data['member_level']=$member_level;
        $data['expire_day']=$expire_day;

        //是否实名认证   是否股东认证   是否开店  店铺地址
        $info=Db::name("partner_certification")->where('member_id',$member_id)->find();
        if(!empty($info)){
            $data['shareholder_status']=$info['status'];
        }else{
            $data['shareholder_status']=0;
        }

        $store=Db::name('store_apply')->where('member_id',$member_id)->find();

        if(!empty($store)){
            $data['store_status']=$store['status'];
            $data['store_address']=$store['address'];
            $data['store_address_detail']=$store['address_detail'];
        }else{
            $data['store_status']=0;
            $data['store_address']='';
            $data['store_address_detail']='';
        }

        //是否申请招商
        $info2=Db::name("attract_invest")->where('member_id',$member_id)->find();
        if(!empty($info2)){
            $data['invest_status']=$info2['status'];
        }else{
            $data['invest_status']=0;
        }

        //当前用户订单数量  待发货  待收货  已完成  退换货
        $count1=Db::name('order')->where(['member_id'=>$member_id,'status'=>2])->count();
        $count2=Db::name('order')->where(['member_id'=>$member_id,'status'=>3])->count();
        $count3=Db::name('order')->where(['member_id'=>$member_id,'status'=>['in',[5,12]]])->count();
        $count4=Db::name('order')->where(['member_id'=>$member_id,'status'=>['in',[8,9,10]]])->count();

        $data['delivered_count']=$count1;
        $data['received_count']=$count2;
        $data['completed_count']=$count3;
        $data['return_count']=$count4;

        //用户信誉保证金
        $data['credit_deposit']=Db::name('member_asset')->where('member_id',$member_id)->value('credit_ensure');


        return $data;
    }

    /**
     * 用户的默认地址或第一个地址
     */
    public function address($member_id){
        $data=Db::name('member_address')->field('ma_id,m_name,m_mobile,location_area,address_detail')
            ->where(['member_id'=>$member_id,'is_default'=>1])->find();
        if(empty($data)){
            $data=Db::name('member_address')->field('m_name,m_mobile,location_area,address_detail')
                ->where(['member_id'=>$member_id])->order('ma_id asc')->find();
        }
        return $data;
    }
    public function collectionLog()
    {
        $member_id =get_header_id("token");
        $data = Db::name("shop_pay p")
            ->field("m.nickName,p.member_id,p.amount,p.pay_score,p.pay_coin,p.pay_wx,p.create_time")
            ->join("mm_member m","m.member_id = p.member_id")
            ->where(['p.status'=>1,'p.store_member_id'=>$member_id])
            ->order(['p.create_time'=>'desc'])
            ->limit(5)
            ->select();
        return $data;
    }

    /**
     * 获取邀请码
     */

    public function getInviteCode($member_id){
        $invt_code=Db::name("member")->where(['member_id'=>$member_id])->value("invt_code");
        return $invt_code;
    }

    /**
     * 我的邀请
     */
    public function getInviter($param,$member_id){
        $type=$param['type'];
        if($type==1){//直推
            $where=[];
            $current_page=$param['current_page'];
            $page_num=$param['page_num'];
            $where['uid_1']=$member_id;
            $data = Db::name("member")
                ->field("member_id,avatarUrl,nickName,mobile")
                ->where($where)
                ->page($current_page,$page_num)
                ->order("member_id desc")
                ->select();
            $tm=time();
            foreach ($data as &$item){
                if(!empty($item['mobile'])){
                    $item['mobile']=substr($item['mobile'],-4);
                }
                //获取会员等级
                $item['member_level']=Db::name("member_grade")->where(['member_id'=>$item['member_id'],'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])->order("grade_type desc,grade_id desc ")->value("grade_type");
                $item['member_level']=empty($item['member_level'])?1:$item['member_level'];
            }


            $total_num = Db::name("member")
                ->where($where)
                ->count();

            $list['current_page'] = $current_page;
            $list['total_page'] = ceil($total_num / $page_num);
            $list['page_num'] = $page_num;
            $list['total_num'] = $total_num;
            $list['data'] = $data;
            return $list;
        }elseif($type==2){//间推
            $where=[];
            $current_page=$param['current_page'];
            $page_num=$param['page_num'];
            $where['uid_2']=$member_id;
            $data = Db::name("member")
                ->field("member_id,avatarUrl,nickName,mobile")
                ->where($where)
                ->page($current_page,$page_num)
                ->order("member_id desc")
                ->select();
            $tm=time();
            foreach ($data as &$item){
                if(!empty($item['mobile'])){
                    $item['mobile']=substr($item['mobile'],-4);
                }
                //获取会员等级
                $item['member_level']=Db::name("member_grade")->where(['member_id'=>$item['member_id'],'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])->order("grade_type desc,grade_id desc ")->value("grade_type");
                $item['member_level']=empty($item['member_level'])?1:$item['member_level'];
            }


            $total_num = Db::name("member")
                ->where($where)
                ->count();
            $list['current_page'] = $current_page;
            $list['total_page'] = ceil($total_num / $page_num);
            $list['page_num'] = $page_num;
            $list['total_num'] = $total_num;
            $list['data'] = $data;
            return $list;
        }elseif($type==3){//邀请我的人
            $tm=time();
            $parentID=Db::name("member")->where(['member_id'=>$member_id])->value("uid_1");

            if($parentID>0){
                $member=Db::name("member")->where(['member_id'=>$parentID])->field("member_id,avatarUrl,nickName,mobile")->find();
                $member['member_level']=Db::name("member_grade")->where(['member_id'=>$parentID,'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])->order("grade_type desc,grade_id desc ")->value("grade_type");
                $member['member_level']=empty($member['member_level'])?1:$member['member_level'];
                if(!empty($member['mobile'])){
                    $member['mobile']=substr($member['mobile'],0,3)."****".substr($member['mobile'],-4)  ;
                }

                $member_info=Db::name("member_info")->where(['member_id'=>$parentID])->field("company,com_post,address,signature")->find();
                if(!empty($member_info)){
                    $member=array_merge($member, $member_info);
                }else{
                    $member['company']='';
                    $member['com_post']='';
                    $member['address']='';
                    $member['signature']='';
                }

            }else{
                $member=[];
            }
            return $member;
        }

    }

    /**
     * 会员升级页面
     */
    public function memberGrade($member_id){
        $tm=time();
        $member=Db::name("member_asset")->where(['member_id'=>$member_id])->field("score,coin")->find();
        if(empty($member)){
            $member['score']=0;
            $member['coin']=0;
        }
        $member['member_level']=Db::name("member_grade")->where(['member_id'=>$member_id,'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])->order("grade_type desc,grade_id desc ")->value("grade_type");
        $member['member_level']=empty( $member['member_level'])?1: $member['member_level'];
        $member['expire_day']='';
        if($member['member_level']!=1){
            $member['expire_day']=Db::name("member_grade")->where(['member_id'=>$member_id,'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])->order("grade_type desc,grade_id desc ")->value("end_time");
        }
        return $member;
    }

    /**
     * 会员升级
     */
    public function gradeHandle($input){
        $tm=time();
        $member_id=$input['member_id'];
        $type=$input['type'];
        if($type==1){//金卡
            //获取上一次有效升级的截止时间
            $end_time=Db::name("member_grade")
                ->where(['member_id'=>$member_id,'grade_type'=>3,'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])
                ->order("grade_type desc,grade_id desc ")->value("end_time");
            if( empty( $end_time)){
                $end_time=time();
            }
            $grade_type=3;
            $amount=Db::name("system_config")
                ->where(['field_name'=>'golden_annual_fee'])
                ->value("field_value");
        }elseif($type==2){//钻卡
            //获取上一次有效升级的截止时间
            $end_time=Db::name("member_grade")
                ->where(['member_id'=>$member_id,'grade_type'=>4,'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])
                ->order("grade_type desc,grade_id desc ")
                ->value("end_time");
            if( empty( $end_time)){
                $end_time=time();
            }
            $grade_type=4;
            $amount=Db::name("system_config")
                ->where(['field_name'=>'drill_annual_fee'])
                ->value("field_value");
        }else{
            returnJson(-2003,'参数错误');
        }
        if($amount<=0){
            returnJson(-2003,'金额无效');
        }
        //获取支付方式
        $pay_method=$input['pay_method'];
        $pay_method_arr=explode(",", $pay_method);
        //获取用户资产
        $coin_money=0;
        $score_money=0;
        $memberAsset=Db::name("member_asset")
            ->where(['member_id'=>$input['member_id']])
            ->field("score,coin")->find();
        //支付金额计算
        if(in_array(1,$pay_method_arr)&&in_array(2,$pay_method_arr)){//积分+金币+微信支付
            if($memberAsset['coin']>$amount){//用户金币足够
                $coin_money=$amount-0.01;
                $wx_money='0.01';
            }else{
                $coin_money=$memberAsset['coin'];
                $orderAmount=$amount-$coin_money;
                if($memberAsset['score']>$orderAmount){
                    $score_money=$orderAmount-0.01;
                    $wx_money='0.01';
                }else{
                    $score_money=$memberAsset['score'];
                    $wx_money=$orderAmount-$memberAsset['score'];
                }
            }
        }elseif(in_array(1,$pay_method_arr)){//积分支付
            if($memberAsset['score']>$amount){
                $score_money=$amount-0.01;
                $wx_money='0.01';
            }else{
                $score_money=$memberAsset['score'];
                $wx_money=$amount-$memberAsset['score'];
            }
        }elseif(in_array(2,$pay_method_arr)){//金币支付
            if($memberAsset['coin']>$amount){
                $coin_money=$amount-0.01;
                $wx_money='0.01';
            }else{
                $coin_money=$memberAsset['coin'];
                $wx_money=$amount-$memberAsset['coin'];
            }
        }else{
            $wx_money=$amount;
        }


        if($amount!=($coin_money+$score_money+$wx_money)){
            returnJson(-2004,'订单金额计算失败');
        }
        $tm=time();

        $end_time+=365*24*3600+strtotime(date('Y-m-d',strtotime('+1 day')))-$tm;


        $order_sn=date("Y").date("m").mt_rand(1,9).date("d").mt_rand(1,9).date("Hi").mt_rand(1000,9999);
        $data=[];
        $data['member_id']=$member_id;
        $data['start_time']=time();
        $data['end_time']=$end_time;
        $data['grade_type']=$grade_type;
        $data['order_sn']=$order_sn;
        $data['amount']=$amount;
        $data['wx_money']=$wx_money;
        $data['score_money']=$score_money;
        $data['coin_money']=$coin_money;
        $data['create_time']=$tm;
        $data['update_time']=$tm;
        $data['status']=2;

        Db::startTrans();
        try{

            $gradeID=Db::name("member_grade_order")->insertGetId( $data);
            if($gradeID<=0){
                throw new Exception("创建订单失败");
            }

            if($score_money>0){//写入积分冻结记录
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$score_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>1,'log_type_id'=>53,
                        'relation_id'=>$gradeID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }

            if($coin_money>0){//写入金币冻结记录
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$coin_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>2,'log_type_id'=>54,
                        'relation_id'=>$gradeID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }

            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score-$score_money,frozen_score=frozen_score+$score_money,
pay_frozen_score=pay_frozen_score+$score_money,coin=coin-$coin_money,frozen_coin=frozen_coin+$coin_money 
where member_id=".$input['member_id']." and score>=$score_money and coin>=$coin_money ";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }
            $result=$this->orderPay($order_sn,$member_id,$wx_money);
            $result['order_sn']=$order_sn;
            Db::commit();
            returnJson(200,'订单创建成功',$result);
        }catch (Exception $e){
            Db::rollback();
            returnJson(2004,'订单创建失败');
        }
    }

    /**
     * 取消支付
     */
    public function cancelOrder($input){

        $order_sn=$input['order_sn'];
        $member_id=$input['member_id'];
        //获取当前记录
        $payInfo=Db::name("member_grade_order")->where(['member_id'=>$member_id,"order_sn"=>$order_sn,'status'=>['not in',[1,3]]])->field("gradeID,score_money,coin_money")->find();
        $coin_money= $payInfo['coin_money'];
        $score_money= $payInfo['score_money'];
        $grade_id= $payInfo['gradeID'];
        Db::startTrans();
        try {
            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score+$score_money,frozen_score=frozen_score-$score_money,pay_frozen_score=pay_frozen_score-$score_money,coin=coin+$coin_money,frozen_coin=frozen_coin-$coin_money where member_id=".$member_id." and frozen_score>=$score_money  and pay_frozen_score>=$score_money and frozen_coin>=$coin_money ";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败");
                }
                $num=Db::name("member_asset_log")->where(['member_id'=>$member_id,'relation_id'=>$grade_id,"log_type_id"=>['in',[53,54]]])->delete();
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }
            $num=Db::name("member_grade_order")->where(['member_id'=>$member_id,"order_sn"=>$order_sn])->update(['status'=>3]);
            if($num<=0){
                throw new Exception("更新失败");
            }

            Db::commit();
            return ['order_sn'=>$order_sn];
        }catch (Exception $e){

            Db::rollback();

            returnJson(-2004,"操作失败");
        }


    }

    /**
     * 会员设置
     */
    public function settting(){

    }

    /**
     * @param $member_id
     * 奖金统计
     */
    public function awardCount($member_id){
        $data=[];
        //旗下会员费总额
        $data['agency_commission_count']=0;
        //注册奖
        $data['reg_award']=Db::name("member_asset_log")->where(['member_id'=>$member_id,'change_type'=>2,'type'=>1,'log_type_id'=>61])->sum("amount");
        //邀请新人奖
        $data['invt_award']=Db::name("member_asset_log")->where(['member_id'=>$member_id,'change_type'=>2,'type'=>1,'log_type_id'=>28])->sum("amount");
        //广告发布奖
        $data['ad_publish_award']=0;
        //发布直推奖
        $data['publish_invt_award']=0;
        //会员升级奖
        $data['grade_award']=Db::name("member_asset_log")->where(['member_id'=>$member_id,'change_type'=>2,'type'=>1,'log_type_id'=>71])->sum("amount");
        //会员升级介推奖
        $data['grade_invt_award']=Db::name("member_asset_log")->where(['member_id'=>$member_id,'change_type'=>2,'type'=>1,'log_type_id'=>1])->sum("amount");
        //会员消费推荐奖
        $data['consume_invt_award']=0;
        //联盟商家招募奖
        $data['recruit_award']=0;
        //消费返利奖
        $data['rebate_award']=0;
        //广告分享金
        $data['ad_share_award']=0;
        //限时特惠两代分享金
        $data['limit_special_award']=0;
        return $data;

    }

    /**
     * 微信支付
     */
    public function orderPay($order_sn,$member_id,$pay_wx){
        #获取openid
        $openid = Db::name("member")
            ->field("openid")
            ->where(['member_id'=>$member_id])
            ->value("openid");
        $total_fee=$pay_wx;

        $body ="会员升级";
        $notify_url =  request()->domain()."/index.php/applet/Notify/gradePayment";
        #调取支付接口
        $weixinPay = new WeixinPay($openid, $body, $total_fee, $order_sn,$notify_url);
        // 发起微信支付
        $result = $weixinPay->pay();
        $result['order_sn']=$order_sn;
        return $result;
    }

    /**
     * 我的招商页面
     */
    public function memberInvest($member_id){

        $member=Db::name('member')
            ->where('member_id',$member_id)
            ->find();

        return $member['mobile'];
    }

    /**
     * 我的招商--提交
     */
    public function investPost($data,$member_id){
        $member=Db::name('member')
            ->where('member_id',$member_id)
            ->find();

        $code = $data['msg_code'];
        #查询验证码是否存在5分钟有效
        $msg_code = Db::name("code_msg")
            ->field("id,code,create_time")
            ->where(['phone'=>$member['mobile'],'status'=>0])
            ->order(['id'=>'desc'])
            ->find();
        if($msg_code === NULL)
        {
            returnJson(-2004,"当前无有效验证码");
        }
        if($msg_code['create_time'] + 5 * 60 < time())
        {
            returnJson(-2004,"当前验证码已过期,请重新发送");
        }
        if($msg_code['code'] != $code)
        {
            returnJson(-2004,"验证码错误");
        }

        //修改验证码状态
        Db::name("code_msg")
            ->where(['id'=>$msg_code['id']])
            ->update(['status'=>1,"update_time"=>time()]);

        //判断用户是否申请过招商
        $count=Db::name('attract_invest')
            ->where('member_id',$member_id)
            ->count();
        if($count>0){
            returnJson(-2004,'已提招商申请');
        }

        $info['invest_name']=$data['invest_name'];
        $info['invest_address']=$data['invest_address'];
        $info['invest_code']=$data['invest_code'];
        $info['member_id']=$member_id;
        $info['status']=2;
        $info['create_time']=time();

        Db::name("attract_invest")
            ->insert($info);

        return true;
    }
}